package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
// @WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1.获取请求url
        String url = request.getRequestURI().toString();
        log.info("请求的url：{}", url);

        // 2.判断url是否包含login 包含则放行
        if(url.contains("login")) {
            log.info("放行");
            filterChain.doFilter(request, response);
            return;
        }

        // 3.获取请求头中的令牌（token）
        String jwt = request.getHeader("token");

        // 4.判断令牌是否存在 如果不存在返回错误结果
        if(!StringUtils.hasLength(jwt)) {
            log.info("token不存在，返回错误信息");
            Result error = Result.error("NOT_LOGIN");
            // 手动把对象转为json字符串
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }

        // 5.解析token 如果解析失败则返回错误信息
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token解析失败，返回错误信息");

            Result error = Result.error("NOT_LOGIN");
            // 手动把对象转为json字符串
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }

        // 6.放行
        log.info("令牌合法 放行");
        filterChain.doFilter(request, response);

    }
}
